<?php

class bwUtils
{
  public static function getAddFieldsContent($id, $rid)
  {
	$c = new Criteria();
  	$c->add(FieldsEntryPeer::ADDITIONAL_FIELDS_ID, $id);
  	$c->add(FieldsEntryPeer::RELATED_ID, $rid);
	
	$addfields = FieldsEntryPeer::doSelect($c);
    return $addfields;
 
  }
  
  public static function getAllAddFieldsDefinition($rel_object)
  {
	$c = new Criteria();
	$c->add(AdditionalFieldsPeer::RELATED, get_class($rel_object));
  	
	$addfields = AdditionalFieldsPeer::doSelect($c);
    
	$arr_of_add_fields = array();
	foreach($addfields as $add_def_fields_object){
		$arr_item['definition'] = $add_def_fields_object;
		
		$item = self::getAddFieldsContent($add_def_fields_object->getId(),$rel_object->getId());
		
		if(!empty($item)){
			$arr_item['content'] = $item[0];
		}else{
			$fields_item = new FieldsEntry();
			$fields_item->setAdditionalFieldsId($add_def_fields_object->getId());
			$fields_item->setRelatedId($rel_object->getId());
			$fields_item->setContent("");
			
			$arr_item['content'] = $fields_item;	
		}
		
		array_push($arr_of_add_fields,$arr_item);
	}
	
	return $arr_of_add_fields;
 
  }

  public static function saveAddFields($rel_object){
  	
  	#print_r(sfContext::getInstance()->getRequest()->getParameter('sf'));
  	#die;  	
	
  	$arr_of_zf_parameter = array();
  	$arr_of_zf_parameter = sfContext::getInstance()->getRequest()->getParameter('zf');
  	
  	foreach($arr_of_zf_parameter as $key => $value_of_zf){
  		$arr_of_parameter_key = split("_",$key);
  		
  		if(!empty($value_of_zf)){
	  		/* Zusatzfeld existiert bereits */
	  		if(!empty($arr_of_parameter_key[1])){
	  			try{
	  				$entryfield_item = FieldsEntryPeer::retrieveByPk($arr_of_parameter_key[1]);
	  			}catch(Exception $e){
	  				sfContext::getInstance()->getController()->setFlash('errMessage', 'Es ist ein interner Fehler aufgetaucht. Bitte wenden Sie sich an die Putzfrau.');
	  				break;
	  			}
	  		}else{
	  			$entryfield_item = new FieldsEntry();
	  		}
	  
		    $entryfield_item->setAdditionalFieldsId($arr_of_parameter_key[0]);
		    $entryfield_item->setRelatedId($rel_object->getId());
		    $entryfield_item->setContent($value_of_zf);
		
		    $entryfield_item->save();
  		}else{
  			if(!empty($arr_of_parameter_key[1])){
	  			try{
	  				$entryfield_item = FieldsEntryPeer::retrieveByPk($arr_of_parameter_key[1]);
	  				$entryfield_item->delete();
	  			}catch(Exception $e){
	  				sfContext::getInstance()->getController()->setFlash('errMessage', 'Es ist ein interner Fehler aufgetaucht. Bitte wenden Sie sich an die Putzfrau.');
	  				break;
	  			}
	  		}			
  			
  		}
  	}
  }
}
